<template>

  <el-form ref="form" label-width="80px" size="mini">
    <el-form-item label="昵称">
      <el-input v-model="userName"></el-input>
    </el-form-item>
    <el-form-item label="头像">
      <el-upload
        class="avatar-uploader"
        action="/api/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="imgUrl" :src="imgUrl" class="avatar" alt=""/>
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <span class="el-upload-list__item-actions">
          点击更换头像
        </span>
    </el-form-item>
    <!--    <img :src="avatar" class="user-avatar">-->
    <el-form-item>
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </el-form-item>
  </el-form>

</template>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      imgUrl: '',
      userName: ''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'avatar'
    ])
  },
  mounted() {
    this.imgUrl = this.avatar
    this.userName = this.name
  },
  methods: {
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.imgUrl = '/api' + res.msg
      } else {
        this.$message.error(res.msg)
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    onSubmit() {
      this.$store.commit('user/SET_AVATAR', this.imgUrl)
      this.$store.commit('user/SET_NAME', this.userName)
      this.closeDialog()
      this.$message.success("保存成功！")
    },
    closeDialog() {
      this.$emit('setDialog', false)
    }
  }
}
</script>
